package com.bee.beemanage.api.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bee.beemanage.api.entity.SysUserLogin;
import com.bee.beemanage.api.service.SysUserLoginService;
import com.bee.beemanage.system.common.utils.redis.RedisUtils;
import com.bee.beemanage.system.common.utils.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import static com.bee.beemanage.system.common.utils.result.ResultTool.success;

@RestController
@RequestMapping("/bee-manage/sys-user-login")
@Api(value ="用户登录表",tags = "用户登录表")
public class SysUserLoginController {

    @Resource
    private SysUserLoginService sysUserLoginService;

    @Resource
    private RedisUtils redisUtils;

    /**
    * 根据id删除用户登录表(用户下线功能)
    * @param id
    * @return
    */
    @ApiOperation(value = "通过id删除用户登录表及缓存", notes = "通过id删除用户登录表及缓存")
    @DeleteMapping("/byId/{id}")
    @PreAuthorize("hasAnyAuthority('sys:userLogin:removeById')")
    public Result removeById(@PathVariable String id) {
        return sysUserLoginService.forceOffline(id);
    }

    /**
     * 根据用户名删除用户登录表(用户下线功能)
     * @param userName 用户名
     * @return 下线是否成功
     */
    @ApiOperation(value = "通过id删除用户登录表及缓存", notes = "通过id删除用户登录表及缓存")
    @DeleteMapping("/byUserName/{userName}")
    @PreAuthorize("hasAnyAuthority('sys:userLogin:removeByUserName')")
    public Result removeByUserName(@PathVariable String userName) {
        return sysUserLoginService.forceOfflineByUsername(userName);
    }
    /**
    * 用户登录表分页查询
    * @param page
    * @param sysUserLogin
    * @return
    */
    @ApiOperation(value = "用户登录表分页查询", notes = "用户登录表分页查询")
    @GetMapping("/page")
    @PreAuthorize("hasAnyAuthority('sys:userLogin:page')")
    public Result page(Page<SysUserLogin> page, SysUserLogin sysUserLogin) {
        return success(sysUserLoginService.page(page, Wrappers.query(sysUserLogin).orderByDesc("create_time")));
    }

    /**
     * 获取令牌信息
     * @param token 令牌
     * @return 令牌信息
     */
    @ApiOperation(value = "获取令牌信息", notes = "获取令牌信息")
    @GetMapping("/getTokenInfo")
    @PreAuthorize("hasAnyAuthority('sys:userLogin:getTokenInfo')")
    public Result getTokenInfo(String token) {
        return success(redisUtils.get("LoginUsers:"+token));
    }
}